using System;
using System.Collections.Generic;
using UnityEngine;

namespace XFFSM
{
    /// <summary>
    /// 状态节点
    /// </summary>
    public class FSMStateNode
    {
        #region 字段 
        /// <summary>
        /// 状态数据
        /// </summary>
        public FSMStateNodeData data; 
        internal RuntimeFSMControllerInstance instance; 
        private List<FSMState> states = new List<FSMState>();

        internal string lastState;
        internal string nextState;
        /// <summary>
        /// 是否正在执行中
        /// </summary>
        internal bool isRuning = false;

        internal bool isFirstEnter = true;

        [Tooltip("当前状态名称Hash,可通过方法FSMController.StringToHash()转换!")]
        public int nameHash;

        #endregion

        #region 方法  
        internal FSMStateNode(FSMStateNodeData data,RuntimeFSMControllerInstance instance) 
        {
            this.data = data;
            this.instance = instance;
            nameHash = FSMController.StringToHash(data.name);

            states.Clear();
            foreach (var item in this.data.StateScripts)
            { 
                Type type = AssemblyTools.GetType(item.className); 
                FSMState state = null;
                if (type != null)
                    state = Activator.CreateInstance(type) as FSMState;

                if (state != null)
                {
                    state.controller = instance.FSMController;
                    state.userData = instance.FSMController.userData;
                    state.currentStateInfo = this;
                    states.Add(state); 
                }
            }

        }

        internal void OnEnter() 
        {
            isRuning = true;
            foreach (var item in this.states)
            {
                item.lastState = lastState;
                item.nextState = nextState;

                if (isFirstEnter) 
                    item.OnCreate(); // 调用 OnCreate 的方法

                item.OnEnter();
            }

            isFirstEnter = false;
        }

        internal void OnExit() 
        { 
            foreach (var item in this.states)
            {
                item.lastState = lastState;
                item.nextState = nextState;
                item.OnExit();
            }
            isRuning = false;
        }

        internal void OnUpdate() 
        {
            foreach (var item in this.states)
            {
                item.OnUpdate();
            } 
        }

        internal void OnFixedUpdate() 
        {
            foreach (var item in this.states)
            {
                item.OnFixedUpdate();
            } 
        }

        internal void OnLateUpdate() 
        {
            foreach (var item in this.states)
            {
                item.OnLateUpdate();
            } 
        }
         
        #endregion
    }

}

